$(document).ready(
    function(){
        
        function isMobile(){
            return $(".windowWidth").css("float") !== "none";
        }
        
        function formatDeviceLayout(){
            var content = $(".responsive-table tbody");
            if(isMobile()){
                $("#search-box").attr("placeholder", "Søk");
            } else{
                content.css("display", "true");
                $("#search-box").attr("placeholder", "Søk etter bar eller sted");
            }
        };
        
        formatDeviceLayout();
        
        $(window).resize(function(){
            formatDeviceLayout();
        });
        
        function getUserPos(){
            var dfd = new $.Deferred();
            var userPos = null;
            
            if(navigator.geolocation){
                navigator.geolocation.getCurrentPosition(
                    function(position){
                        userPos = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
                        dfd.resolve(userPos);
                    }
                );
            } else{
                dfd.resolve(userPos);
            }
            
            return dfd.promise();
        }
        
        function initialize(args, centerFirstResult) {
            $.when(getUserPos()).then(
                function(userItems){
                    
                    if(!centerFirstResult && $("#search-box").val().length > 0){
                        return;
                    }
            
                    var myPos = {
                        lat: Number(userItems.k),
                        lng: Number(userItems.D)
                    };
                    
                    var fPos = args[0].latlong.substring(1,args[0].latlong.length-1).split(",");
                    var firstPos = {
                        lat: Number(fPos[0]),
                        lng: Number(fPos[1])
                    }
                    
                    var center = centerFirstResult ? firstPos : myPos;
                    
                    var mapOptions = {
                        center: center,
                        zoom: 13
                    };
                    
                    var map = new google.maps.Map(document.getElementById('map-canvas'),
                        mapOptions);
                     
                    var barMarker = [];
                    var barInfoWindow = [];
                    
                    for(var i=0; i< args.length; i++){
                        var latLng = args[i].latlong.substring(1,args[i].latlong.length-1).split(",");
                        var latLong = {
                            lat: Number(latLng[0]),
                            lng: Number(latLng[1])
                        };
                        
                        barMarker[i] = new google.maps.Marker({
                            position: latLong,
                            map: map,
                            title: args[i].name
                            //,icon: image
                        });
                        
                        var infoImg = args[i].image ? "<img src='data:" + args[i].image_type + ";base64," + args[i].image + "' class='info-window-img'/>" : "<img src='../resources/images/vikinghelmet.png' class='info-window-img'/>";
                        
                        var barContentString = "<div class='marker-info'>" + infoImg + "<span class='info-window-header'>" + args[i].name + "</span><div class='info-window-descr'>" + args[i].description + "</div></div>";
                        
                        barInfoWindow[i] = new google.maps.InfoWindow({
                            content: barContentString
                        });
                        
                        google.maps.event.addListener(barMarker[i], 'click', function(w) {
                            return function(){
                                for(var g=0; g<barMarker.length; g++){
                                    barInfoWindow[g].close(map, barMarker[g]);
                                }
                                barInfoWindow[w].open(map, barMarker[w]);
                            }
                        }(i));
                    }
                    
                    
                    if(userItems){
                        var userMarker = new google.maps.Marker({
                            position: userItems,
                            map: map,
                            title: "Din posisjon"
                            //,icon: image
                        });
                    }
                
                    var userContentString = "<div class='marker-info'>Din posisjon.</div>";
                    
                    var userInfoWindow = new google.maps.InfoWindow({
                        content: userContentString
                    });
                    
                    google.maps.event.addListener(userMarker, 'click', function() {
                        userInfoWindow.open(map, userMarker);
                    });
                }
            );
        }
        
        var UI = {};
        (function (UI) {
            
            UI.start = function(){
                Controller.init();
                
                //Check if URL Parameter 'search' is defined.
                var searchParam = window.location.href.split("#search=")[1];
                if(searchParam){
                    var search = searchParam.split("=")[0];
                    $("#search-box").val(search);
                    $("#searchBtn").click().focus();
                    window.location.href = "#";
                }
                
                var args = {
                    action : 'Select'
                };
                
                $.when(Actions.barOverviewFetch(args), Actions.getPlaces(args)).then(function(barItems, placeItems) {
                    var tags = [];
                    for(var bar in barItems){
                        var bar = barItems[bar];
                        tags.push({label : bar.name, desc : "Bar"});
                    }
                    
                    for(var place in placeItems){
                        var place = placeItems[place];
                        var name = place.name;
                        
                        name = name.toLowerCase().replace(/([^a-zæøå])([a-zæøå])(?=[a-zæøå]{2})|^([a-zæøå])/g, function(_, g1, g2, g3) {
                            return (typeof g1 === 'undefined') ? g3.toUpperCase() : g1 + g2.toUpperCase();
                        });
                        tags.push({label : name, desc : "Sted"});
                    }
                    
                    $("#search-box").autocomplete({
                        source: tags,
                        open: function(){
                            if($(".windowWidth").css("float") === "none" ){
                                $(".ui-menu-item").width($("#search-box").width());
                            } else{
                                $(".ui-menu-item").width($(window).width());
                            }
                        },
                        select: function(event, ui){
                            $("#search-box").val(ui.item.value);
                            $("#searchBtn").click();
                        }
                    }).autocomplete("instance")._renderItem  = function(li, item){
                        return $("<li>").append("<span class='item-label'>" + item.label + "</span><span class='item-desc'>" + item.desc + "</span>").appendTo(li);
                    };
                    initialize(barItems, false);
                });
                
            };
            
        }(UI));
        var Helpers = {};
        (function (Helpers) {
            
            
        }(Helpers));
        
        var Actions = {};
        (function (Actions) {
            
            Actions.getBarsInCity = function(args) {
                var dfd = new $.Deferred();
                console.log("%c runSQL getBarsInCity", "color: green");
                $.ajax({
                    type: "GET",
                    url: "../resources/helpers/getBarsInCity.php",
                    data: args,
                    cache: false,
                    success: function(data){
                        console.log("%c Returned from getBarsInCity:","color: green");
                        data = JSON.parse(data);
                        dfd.resolve(data);
                    }
                });
                return dfd.promise();
            };
            
            Actions.getPlaces = function(args) {
                var dfd = new $.Deferred();
                $.ajax({
                    type: "GET",
                    url: "../resources/helpers/getPlaces.php",
                    data: args,
                    cache: false,
                    success: function(data){
                        data = JSON.parse(data);
                        dfd.resolve(data);
                    }
                });
                return dfd.promise();
            };
            
            Actions.barOverviewFetch = function(args) {
                var dfd = new $.Deferred();
                $.ajax({
                    type: "GET",
                    url: "../resources/helpers/barOverviewFetch.php",
                    data: args,
                    cache: false,
                    success: function(data){
                        data = JSON.parse(data);
                        dfd.resolve(data);
                    }
                });
                return dfd.promise();
            };
            
            Actions.getBarSearchResults = function(args) {
                var dfd = new $.Deferred();
                $.ajax({
                    type: "GET",
                    url: "../resources/helpers/getBarSearchResults.php",
                    data: args,
                    cache: false,
                    success: function(data){
                        data = JSON.parse(data);
                        dfd.resolve(data);
                    }
                });
                return dfd.promise();
            };
            
        }(Actions));
        
        var Controller = {};
        (function (Controller) {
            
            var placeClicked = function(cityArgs){
                $("button.place-btn").each(function(){
                    $(this).removeClass("place-btn-active");
                });
                $("#" + cityArgs.id).addClass("place-btn-active");
                
                var args = {
                    action: 'get',
                    place : cityArgs.place
                };
                
                $.when(Actions.getBarsInCity(args)).then(
                    function(bars){
                        var html = "<tr><td style='font-size: 14px; text-align: right;padding-right: 10px;'>Mangler noe? <a href='../pages/registerBar.php'>Registrer en bar her</a></td></tr>";
                        html += "<tr><td>";
                        for(b in bars){
                            var b = bars[b];
                            var ratingStars = setRatingStars(b.rating);
                            html += "<tr><td class='bar-row'><a href='../pages/barProfile.php?barid=" + b.bar_id + "'>" + b.name + "</a> <span class='rating-stars'>" + ratingStars + "</span><br>" + b.address + "<br>" + b.postal_no + " " + b.place + "</td></tr>";
                        }
                        $("#results").html(html);
                        initialize(bars, true);
                    }
                );
            };
            
            function setRatingStars(rating){
                var rating = Number(rating);
                $("#rating").attr("title", rating + " / 5");
                var html = "";
                var counter = 1;
                while(counter <= 5){
                    if(rating >= counter){
                        html += "<img id='star" + counter + "' class='rating-star' src='../resources/images/rating-star.png'>";
                    } else {
                        html += "<img id='star" + counter + "' src='../resources/images/rating-star.png' class='grayscale rating-star'>";
                    }
                    counter++;
                }
                return html;
                //$("#rating" + rowNo).html(html);
            }
            
            function searchBtnClicked(){
                var args = {
                    action : "select",
                    searchvalue : $("#search-box").val()
                };
                $.when(Actions.getBarSearchResults(args)).then(
                    function(bars){
                        var html = "<tr><td style='font-size: 14px; text-align: right;padding-right: 10px;'>Mangler noe? <a href='../pages/registerBar.php'>Registrer en bar her</a></td></tr>";
                        html += "<tr><td>";
                        for(b in bars){
                            var b = bars[b];
                            var ratingStars = setRatingStars(b.rating);
                            html += "<tr><td class='bar-row'><a href='../pages/barProfile.php?barid=" + b.bar_id + "'>" + b.name + "</a> <span class='rating-stars'>" + ratingStars + "</span><br>" + b.address + "<br>" + b.postal_no + " " + b.place + "</td></tr>";
                        }
                        $("#results").html(html);
                        initialize(bars, true);
                    }
                );
            }
            
            Controller.init= function(){
                $("#findTrondheim").unbind("click").bind("click", function(){ var args = {place : 'TRONDHEIM', id: event.target.id}; placeClicked(args);});
                $("#findLarvik").unbind("click").bind("click", function(){ var args = {place : 'LARVIK', id: event.target.id}; placeClicked(args);});
                $("#findOslo").unbind("click").bind("click", function(){ var args = {place : 'OSLO', id: event.target.id}; placeClicked(args);});
                $("#findStavanger").unbind("click").bind("click", function(){ var args = {place : 'STAVANGER', id: event.target.id}; placeClicked(args);});
                $("#findBergen").unbind("click").bind("click", function(){ var args = {place : 'BERGEN', id: event.target.id}; placeClicked(args);});
                $("#findTromso").unbind("click").bind("click", function(){ var args = {place : 'TROMSØ', id: event.target.id}; placeClicked(args);});
                $("#searchBtn").unbind("click").bind("click", searchBtnClicked);
                $(document).keypress(function(e){
                    if(e.which === 13 && $("#search-box").is(":focus")){
                        $("#searchBtn").click().focus();
                    }
                });
            };
            
        }(Controller));	
        
//        $.when(UI.start()).then(
//            function(){
//                Controller.init();
//            }
//        );
        UI.start();
    }
);